package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.CheckGroupDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import com.itheima.service.CheckGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;

@Service(interfaceClass = CheckGroupService.class)
@Transactional
public class CheckGroupServiceImpl implements CheckGroupService {
    @Autowired
    CheckGroupDao checkGroupDao;

    @Override
    public void addGroup(CheckGroup checkGroup, Integer[] checkitemIds) {
        checkGroupDao.addNewGroup(checkGroup);

        //获取生成的id
        Integer id = checkGroup.getId();
        setCheckGroupRelationCheckItem(id,checkitemIds);

    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        /*分页*/
        PageHelper.startPage(currentPage,pageSize);

        Page<CheckGroup> page = checkGroupDao.findCheckGroupByCondition(queryString);

        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public CheckGroup findCheckGroupById(Integer checkGroupId) {
        CheckGroup checkGroup = checkGroupDao.findCheckGroupById(checkGroupId);
        System.out.println(checkGroup);
        return checkGroup;
    }

    @Override
    public List<Integer> findCheckItemById(Integer checkGroupId) {
        List<Integer> checkitemIds = checkGroupDao.findItemIdsByGroupId(checkGroupId);
        return checkitemIds;
    }

    @Override
    public void editGroupAndSave(CheckGroup checkGroup, Integer[] checkitemIds) {

        Integer id = checkGroup.getId();

        checkGroupDao.deleteAssolication(id);

        checkGroupDao.saveEditCheckGroup(checkGroup);

        setCheckGroupRelationCheckItem(id,checkitemIds);

    }

    public void setCheckGroupRelationCheckItem(Integer id, Integer[] checkitemIds){
        for (Integer checkitemId : checkitemIds) {
            HashMap<String, Integer> map = new HashMap<>();
            map.put("CheckGroupId",id);
            map.put("checkitemId",checkitemId);
            checkGroupDao.addNewAssociation(map);
        }
    }

    @Override
    public List<CheckGroup> findAll() {
        List<CheckGroup> checkGroupList = checkGroupDao.findAll();
        return checkGroupList;
    }




}
